/* Created by jankoatwarpspeed.com */
/* modified by thiagobraga */
(function ($) {
  $.fn.formToWizard = function(options) {
    options = $.extend({
      submitButton: ''
    }, options);

    var element = this,
    steps = $(element).find("fieldset"),
    count = steps.size(),
    submitButtonName = "#" + options.submitButton,

    createPrevButton = function (i) {
      var stepName = "step" + i;
      $("#"+ stepName +"commands").append("<a href='#' id='"+ stepName +"Prev' class='btn'><i class='icon-black icon-chevron-left'></i> Anterior</a>");

      $("#"+ stepName +"Prev").bind("click", function(e) {
        e.preventDefault();
        $("#"+ stepName).hide();
        $("#step" + (i - 1)).show();
        $(submitButtonName).hide();
        selectStep(i - 1);
      });
    },

    createNextButton = function (i) {
      var stepName = "step" + i;
      $("#"+ stepName +"commands").append("<a href='#' id='"+ stepName +"Next' class='btn pull-right'>Próximo <i class='icon-black icon-chevron-right'></i></a>");

      $("#"+ stepName +"Next").on('click', function(e) {
        e.preventDefault();
        $("#"+ stepName).hide();
        $("#step"+ (i + 1)).show();
        if (i + 2 == count)
          $(submitButtonName).appendTo('.form-actions div').show();
        selectStep(i + 1);
      });
    },

    selectStep = function (i) {
      $("#steps li").removeClass("current");
      $("#stepDesc"+ i).addClass("current");
    };

    $(submitButtonName).hide();
    $(element).before("<ul id='steps'></ul>");

    steps.each(function(i) {
      $(this).wrap("<div id='step" + i + "' class='step'></div>");
      $(this).parent().append("<div class='form-actions'><div id='step" + i + "commands'></div></div>");

      var name = $(this).find("legend").html();
      $("#steps").append("<li id='stepDesc" + i + "'>Passo " + (i + 1) + "<span>" + name + "</span></li>");

      if (i == 0) {
        createNextButton(i);
        selectStep(i);
      }
      else if (i == count - 1) {
        $("#step" + i).hide();
        createPrevButton(i);
      }
      else {
        $("#step" + i).hide();
        createPrevButton(i);
        createNextButton(i);
      }
    });

  }
})(jQuery);